import React, { FC, useEffect, RefObject, useRef, memo, useCallback } from 'react';
import styles from '../index.less';
import { Form } from 'antd';
import { settingMap } from '../constants/FormMap';

interface ISetting {
    data: any,
    changeSettingVisible: (visible: boolean) => void,
    settingVisible: boolean
}
const Setting: FC<ISetting> = (props) => {
    const { data, changeSettingVisible, settingVisible } = props;
    const settingRef = useRef<HTMLDivElement | null>(null);
    
    const listener = (event: MouseEvent) => {
      event.stopPropagation();
      // 做ref.current（目标元素）和事件目标的nullish coalescing
      const domElement = settingRef.current;
      console.log(event.target, event.target?.dataset, "dataset")
     // 如果点击的不是目标元素本身或其子元素，则调用handler
     if (!domElement || (!domElement?.contains(event.target as Node) && event.target?.dataset?.useabledEle !== 'on')) {
        settingRef.current = null;
        changeSettingVisible(false);
     }
   }
    useClickOutside(listener, settingVisible, settingRef);


    return (
        <div className={styles.setting} ref={settingRef}>
            <Form>
                {}
            </Form>
        </div>
    )
};


export default memo(Setting, (oldProps: Readonly<ISetting>, newProps: Readonly<ISetting>) => {
  if(JSON.stringify(oldProps) === JSON.stringify(newProps)) {
    return true;
  }
  return false
});

// 定义handler的类型
type ClickOutsideHandler = (event?: MouseEvent) => void;
const useClickOutside = (listener:ClickOutsideHandler, visible: boolean, domElement) => { 
  useEffect(() => {
      console.log('绑定', domElement.current)
      if(domElement.current) {
        // 在document上添加事件监听
        visible && document.addEventListener('mousedown', listener);
      }
      // 在组件卸载时移除事件监听
      return () => {
        console.log('移除');
        if(visible) {
          document.removeEventListener('mousedown', listener);
        }
      };
    }, [listener, visible]); // 依赖项数组，当ref或handler变化时重新运行effect
  };
  